var express = require("express");
var router = express.Router();
var {
  UserModel,
  RoleModel,
  AnnoModel,
  AdviseModel,
  NucModel,
  VacModel,
  TraModel,
  GoodsModel,
  CartModel,
  BillModel,
} = require("../mongo/model");
var { createToken, checkToken } = require("../utils/token");
var {
  FindOneTableData,
  FindAllTableData,
  UpdateManyTableData,
  InsertManyTableData,
  RemoveTableData,
} = require("../mongo/index");
var axios = require("axios"); //express中发起请求
var multer = require("multer"); //上传文件

router.all("/test", (req, res) => {
  res.json({
    code: 200,
    msg: "这是一个vue - api 测试接口",
    result: {},
  });
});

router.all("/register", (req, res) => {
  var body = req.body;
  UserModel.findOne({
    $or: [
      {
        username: body.username,
      },
      {
        phone: body.phone,
      },
    ],
  })
    .then((result) => {
      if (result) {
        res.json({
          code: 301,
          msg: "用户已经被注册，请重新注册",
          result,
        });
      } else {
        body.time = new Date();
        UserModel.insertMany(body).then((data) => {
          res.json({
            code: 200,
            msg: "注册成功",
            result: data,
          });
        });
      }
    })
    .catch((err) => {
      res.json({
        code: 500,
        msg: "服务器异常",
        err,
        result: null,
      });
    });
});

router.all("/login", (req, res) => {
  var body = req.body;
  UserModel.findOne({
    //未封装的查询方法，手写
    password: body.password, //以密码与用户名（可能是手机号也可能是用户名）来查询
    $or: [
      {
        username: body.account,
      },
      {
        phone: body.account,
      },
    ],
  })
    .then((result) => {
      if (result) {
        //有结果，数据库中查到了。就登陆成功
        const token = createToken({
          //生成一个token
          username: result.username,
          phone: result.phone,
          password: result.password,
        });
        res.json({
          code: 200,
          msg: "登陆成功",
          result: result,
          token,
        });
      } else {
        //数据库中没查到，账号错误或密码错误或都错误
        res.json({
          code: 401,
          msg: "登陆失败，账号或密码错误",
          result: null,
        });
      }
    })
    .catch((err) => [
      res.json({
        code: 500,
        msg: "服务器异常",
        err,
        result: null,
      }),
    ]);
});
// 没有带斜杠。一定要带斜杠
router.all("/getcaptcha", (req, res) => {
  const { phone } = req.body; //解构？
  FindOneTableData({
    //封装的查找一个的方法
    model: UserModel,
    res, //盲猜是请求完得到的数据
    query: {
      phone: phone,
    },
    next(result) {
      //先凭借手机号在数据库查询，有结果就证明注册过，可发送验证码
      if (result) {
        //查到了，发送验证码
        axios
          .get("http://121.196.235.163:3000/captcha/sent", {
            params: {
              phone,
            },
          })
          .then((data) => {
            if (data.data.code == 200) {
              //结果包裹多层，所以需要多点几个data
              res.json({
                code: 200,
                msg: "验证码发送成功",
              });
            } else {
              res.json({
                code: 402,
                msg: "验证码发送失败",
              });
            }
          })
          .catch((err) => {
            res.json({
              code: 500,
              err,
              msg: "未知错误-网易云接口异常",
            });
          });
      } else {
        res.json({
          //数据库查询结果为空，没这个手机号
          code: 401,
          msg: "手机号还没注册哦，请先注册",
        });
      }
    },
  });
});
// 只要生成了token就可以获得用户信息了
router.all("/getuserinfo", (req, res) => {
  checkToken(req, res, ({ username, phone, password }) => {
    FindOneTableData({
      model: UserModel,
      res,
      query: {
        username,
      },
    });
  });
});

// 校验验证码
router.all("/checkcaptcha", (req, res) => {
  const { phone, captcha } = req.body;
  FindOneTableData({
    //校验验证码之前先判断数据库有没有这个用户
    model: UserModel,
    res,
    query: {
      phone: phone,
    },
    next(result) {
      if (result) {
        // 校验验证码
        axios
          .get("http://121.196.235.163:3000/captcha/verify", {
            params: {
              phone,
              captcha,
            },
          })
          .then((data) => {
            if (data.data.code == 200) {
              // token
              const token = createToken({
                username: result.username,
                phone: result.phone,
                password: result.password,
              });
              res.json({
                code: 200,
                msg: "验证码校验成功",
                result, //不把result带过来，获取不到里面的phone
                token,
              });
            } else {
              res.json({
                code: 402,
                msg: "验证码校验失败",
              });
            }
          })
          .catch((err) => {
            res.json({
              code: 500,
              err,
              msg: "未知错误-网易云接口异常",
            });
          });
      } else {
        res.json({
          code: 401,
          msg: "手机号还没有注册哦,请先注册",
        });
      }
    },
  });
});

// 找回密码
router.all("/findpass", (req, res) => {
  const { phone, captcha, newpass } = req.body;
  FindOneTableData({
    //校验验证码之前先判断数据库有没有这个用户
    model: UserModel,
    res,
    query: {
      phone: phone,
    },
    next(result) {
      if (result) {
        //有这个用户就开始校验验证码
        axios
          .get("http://121.196.235.163:3000/captcha/verify", {
            params: {
              phone,
              captcha,
            },
          })
          .then((data) => {
            if (data.data.code == 200) {
              //校验通过，执行修改密码
              UpdateManyTableData({
                model: UserModel,
                res,
                query: { phone },
                data: {
                  password: newpass,
                },
                msg: "找回密码成功",
              });
              //  不需要那么多报告，报告多了会报错
              // res.json({
              //   code: 200,
              //   msg: "验证码校验成功",
              //   result,
              //   token,
              // });
            } else {
              res.json({
                code: 402,
                msg: "验证码校验失败",
              });
            }
          })
          .catch((err) => {
            res.json({
              code: 500,
              err,
              msg: "未知错误-网易云接口异常",
            });
          });
      } else {
        res.json({
          code: 401,
          msg: "手机号还没有注册哦,请先注册",
        });
      }
    },
  });
});

// 主页中的修改密码
router.all("/changepass", (req, res) => {
  const { account, oldpass, newpass } = req.body;
  FindOneTableData({
    model: UserModel,
    res,
    query: {
      $or: [
        {
          username: account,
        },
        {
          phone: account,
        },
      ],
      password: oldpass,
    },
    next(result) {
      if (result) {
        //查到了，证明有这个用户，执行修改
        UpdateManyTableData({
          model: UserModel,
          res,
          query: { phone: result.phone }, //通过手机号来查到要修改的数据
          data: {
            password: newpass, //修改的数据
          },
          msg: "修改密码成功！",
        });
      } else {
        //没查到，没这个用户
        res.json({
          //数据库查询结果为空，没这个手机号
          code: 401,
          msg: "输入错误，请重新输入",
        });
      }
    },
  });
});
// 首页头部的修改密码 ,路径名就不叫changepass而是叫changepasst
router.all("/changepasst", (req, res) => {
  const { oldpass, newpass } = req.body;
  checkToken(req, res, ({ password, username, phone }) => {
    if (oldpass == password) {
      // 修改密码
      UpdateManyTableData({
        model: UserModel,
        res,
        query: { username }, //通过什么找到那条数据。难道是键名键值一样所以可以简写？
        data: {
          password: newpass, //修改的数据
        },
      });
    } else {
      res.json({
        code: 401,
        msg: "旧密码不匹配,请重试",
        result: {},
      });
    }
  });
});
// 上传文件
const storage = multer.diskStorage({
  //保存路径
  destination: function (req, file, cb) {
    cb(null, "public/upload");
    //注意这里的文件路径,不是相对路径，直接填写从项目根路径开始写就行了
  },
  //保存在 destination 中的文件名
  filename: function (req, file, cb) {
    cb(null, "WUHAN2209__" + Date.now() + "__" + file.originalname); // 1.png => WUHAN2209__1571234983991.jpg 避免文件名称冲突
  },
});

const upload = multer({ storage: storage }).any();

router.post("/uploadfile", upload, (req, res) => {
  checkToken(req, res, () => {
    var files = req.files;
    var path = files[0].path; //服务器路径
    res.json({
      code: 200,
      msg: "上传成功",
      path,
      result: {},
    });
  });
});

// 修改用户信息
router.post("/changeuser", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({ username }) => {
    UpdateManyTableData({
      model: UserModel,
      res,
      query: { username },
      data: body,
    });
  });
});
// 下面四个大同小异的
// 添加公告
router.post("/annoadd", (req, res) => {
  const body = req.body;
  checkToken(req, res, (author) => {
    body.time = new Date();
    body.author = author; //解析token，得到个人信息，把个人信息存到这条数据中
    InsertManyTableData({
      model: AnnoModel,
      res,
      data: body,
    });
  });
});

// 公告列表
router.post("/annolist", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //没有限制，读取所有的公告
    FindAllTableData({
      model: AnnoModel,
      res,
      msg: "查询公告成功",
    });
  });
});

// 公告修改
router.post("/annoupdate", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    body.time = new Date();
    UpdateManyTableData({
      model: AnnoModel,
      res,
      query: { _id: body._id }, //通过query找到要修改的数据
      data: body,
    });
  });
});

// 公告删除
router.post("/annodelete", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //空着是因为不需要解析token得到用户名、手机号、密码
    RemoveTableData({
      model: AnnoModel,
      res,
      query: body,
    });
  });
});
// 下面四个大同小异的
// 添加意见
router.post("/adviseadd", (req, res) => {
  const body = req.body;
  checkToken(req, res, (author) => {
    body.time = new Date();
    body.author = author; //解析token，得到个人信息，把个人信息存到这条数据中
    InsertManyTableData({
      model: AdviseModel,
      res,
      data: body,
    });
  });
});

// 意见列表
router.post("/adviselist", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //没有限制，读取所有的公告
    FindAllTableData({
      model: AdviseModel,
      res,
      msg: "查询意见成功",
      query: {
        title: new RegExp(body.keyword),
      },
    });
  });
});

// 意见修改
router.post("/adviseupdate", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    body.time = new Date();
    UpdateManyTableData({
      model: AdviseModel,
      res,
      query: { _id: body._id }, //通过query找到要修改的数据
      data: body,
    });
  });
});

// 意见删除
router.post("/advisedelete", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //空着是因为不需要解析token得到用户名、手机号、密码
    RemoveTableData({
      model: AdviseModel,
      res,
      query: body,
    });
  });
});
// 下面三个核酸、出行、疫苗大同小异的。都是用来新增、查询、删除
// 新增核酸状态
router.post("/nucadd", (req, res) => {
  const body = req.body;
  checkToken(req, res, (author) => {
    body.author = author; //解析token，得到个人信息，把个人信息存到这条数据中
    InsertManyTableData({
      model: NucModel,
      res,
      data: body,
    });
  });
});

// 核酸状态列表
router.post("/nuclist", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({ phone }) => {
    //没有限制，读取所有的公告
    FindAllTableData({
      model: NucModel,
      res,
      query: { "author.phone": phone }, //只能看到自己的
      msg: "查询核酸状态成功",
    });
  });
});

// 意核酸状态删除
router.post("/nucdelete", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //空着是因为不需要解析token得到用户名、手机号、密码
    RemoveTableData({
      model: NucModel,
      res,
      query: body,
    });
  });
});
// 大同小异的
// 新增疫苗状态
router.post("/vacadd", (req, res) => {
  const body = req.body;
  checkToken(req, res, (author) => {
    body.author = author; //解析token，得到个人信息，把个人信息存到这条数据中
    InsertManyTableData({
      model: VacModel,
      res,
      data: body,
    });
  });
});

// 疫苗状态列表
router.post("/vaclist", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({ phone }) => {
    //没有限制，读取所有的公告
    FindAllTableData({
      model: VacModel,
      res,
      query: { "author.phone": phone }, //只能看到自己的
      msg: "查询疫苗状态成功",
    });
  });
});

// 疫苗状态删除
router.post("/vacdelete", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //空着是因为不需要解析token得到用户名、手机号、密码
    RemoveTableData({
      model: VacModel,
      res,
      query: body,
    });
  });
});
// 大同小异的
// 新增出行状态
router.post("/traadd", (req, res) => {
  const body = req.body;
  checkToken(req, res, (author) => {
    // body.time = new Date();//事件是自己传进去的时间
    body.author = author; //解析token，得到个人信息，把个人信息存到这条数据中
    InsertManyTableData({
      model: TraModel,
      res,
      data: body,
    });
  });
});

// 出行状态列表
router.post("/tralist", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({ phone }) => {
    //没有限制，读取所有的公告
    FindAllTableData({
      model: TraModel,
      res, //报错的原因就是少了res，没了res就不返回结果
      msg: "查询出行状态成功",
      query: { "author.phone": phone }, //只能看到自己的
    });
  });
});

// 出行状态删除
router.post("/tradelete", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //空着是因为不需要解析token得到用户名、手机号、密码
    RemoveTableData({
      model: TraModel,
      res,
      query: body,
    });
  });
});

// 查询商品列表
router.post("/goodslist", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //没有限制，读取所有的公告
    FindAllTableData({
      model: GoodsModel,
      res, //报错的原因就是少了res，没了res就不返回结果
      msg: "查询商品成功",
    });
  });
});

// 下面四个大同小异的
// 加入购物车
router.post("/cartadd", (req, res) => {
  const body = req.body;
  checkToken(req, res, (buyer) => {
    body.buyer = buyer; //解析token，得到个人信息，把个人信息存到这条数据中
    InsertManyTableData({
      //个人信息、商品信息、数量。checked可以后面加
      model: CartModel,
      res,
      data: body,
    });
  });
});

// 查询购物车
router.post("/cartlist", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({ phone }) => {
    FindAllTableData({
      model: CartModel,
      res,
      query: body.id
        ? { "buyer.phone": phone, "good.id": body.id }
        : { "buyer.phone": phone },
    });
  });
});

// 修改购物车
router.post("/cartupdate", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({ phone }) => {
    UpdateManyTableData({
      model: CartModel,
      res,
      query: { "buyer.phone": phone, _id: body.id }, //通过query找到要修改的数据
      data: body,
    });
  });
});

//  删除购物车
router.post("/cartdelete", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //空着是因为不需要解析token得到用户名、手机号、密码
    RemoveTableData({
      model: CartModel,
      res,
      query: body, //根据购物车数据的id删除
    });
  });
});

// 下面三个大同小异的
// 加入订单
router.post("/billadd", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    InsertManyTableData({
      model: BillModel,
      res,
      data: body,
    });
  });
});

// 查询订单
router.post("/billlist", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({ phone }) => {
    FindAllTableData({
      model: BillModel,
      res,
      query: { "buyer.phone": phone },
    });
  });
});
//  删除订单
router.post("/billdelete", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    RemoveTableData({
      model: BillModel,
      res,
      query: body, //根据订单数据的id删除
    });
  });
});
// 修改订单
router.post("/billupdate", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({ phone }) => {
    UpdateManyTableData({
      model: BillModel,
      res,
      query: { _id: body._id }, //通过query找到要修改的数据
      data: body,
    });
  });
});
// 下面四个用户方法
// 添加用户
router.post("/useradd", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({ username, phone, password }) => {
    FindOneTableData({
      model: UserModel,
      res,
      query: {
        $or: [
          {
            username: body.username,
          },
          {
            phone: body.phone,
          },
        ],
      },
      next(result) {
        if (result) {
          res.json({
            code: 401,
            msg: "添加失败,用户名或者手机已经被添加",
            result: null,
          });
        } else {
          body.time = new Date();
          InsertManyTableData({
            model: UserModel,
            res,
            data: body,
          });
        }
      },
    });
  });
});
// 用户列表
router.post("/userlist", (req, res) => {
  const body = req.body;
  let query = {};

  // 搜索条件
  if (body.keyword && body.role) {
    query = {
      role: body.role,
      $or: [
        {
          username: new RegExp(body.keyword), // 用户名
        },
        {
          phone: new RegExp(body.keyword), // 手机号
        },
      ],
    };
  } else if (body.role) {
    query = {
      role: body.role,
    };
  } else if (body.keyword) {
    query = {
      $or: [
        {
          username: new RegExp(body.keyword), // 用户名
        },
        {
          phone: new RegExp(body.keyword), // 手机号
        },
      ],
    };
  }
  checkToken(req, res, ({}) => {
    FindAllTableData({
      model: UserModel,
      res,
      msg: "查询成功",
      query: query,
    });
  });
});
// 人员修改
router.post("/userupdate", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    FindOneTableData({
      model: UserModel,
      res,
      query: {
        $or: [
          {
            username: body.username,
          },
          {
            phone: body.phone,
          },
        ],
      },
      // 这里有个bug，用户名和手机号需要同时修改。改为可以修改其中一个
      // 如果有结果，并且不是用户名和手机号其中一个值相等另一个值不相等
      next(result) {
        if (
          result &&
          result.phone !== body.phone &&
          result.username !== body.username
        ) {
          res.json({
            code: 401,
            msg: "用户名或者手机号已存在,请重新修改",
            result: null,
          });
        } else {
          UpdateManyTableData({
            model: UserModel,
            res,
            query: {
              _id: body._id,
            },
            data: body,
          });
        }
      },
    });
  });
});

// 人员删除
router.post("/userdelete", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    RemoveTableData({
      model: UserModel,
      res,
      query: body,
    });
  });
});
// 下面四个，大同小异
// 权限，增删改查
router.all("/getrolelist", (req, res) => {
  var body = req.body;
  checkToken(req, res, () => {
    FindAllTableData({
      model: RoleModel,
      res,
      query: {
        //模糊查询，参数可传可不传
        // $or:[
        //   {
        //     label: new RegExp(body.keyword),
        //   },{
        //     value: (new RegExp(body.keyword))/1,
        //   }
        // ]
        label: new RegExp(body.keyword),
      },
      msg: "角色列表获取成功",
    });
  });
});
// 增加权限角色
router.post("/roleadd", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    //不需要token中的用户信息
    FindOneTableData({
      model: RoleModel,
      res,
      query: {
        $or: [
          {
            value: body.value, //不能权限名或者权限值相同
          },
          {
            label: body.label,
          },
        ],
      },
      next(result) {
        if (result) {
          res.json({
            code: 401,
            msg: "添加失败，已存在",
            result: null,
          });
        } else {
          InsertManyTableData({
            model: RoleModel,
            res,
            data: body,
          });
        }
      },
    });
  });
});
// 权限删除
router.post("/roledelete", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    RemoveTableData({
      model: RoleModel,
      res,
      query: body,
    });
  });
});
// 权限修改
router.post("/roleupdate", (req, res) => {
  const body = req.body;
  checkToken(req, res, ({}) => {
    UpdateManyTableData({
      model: RoleModel,
      res,
      query: {
        _id: body._id,
      },
      data: body,
    });
  });
});
// react项目中请求商品数据
router.all("/getgoodlist", (req, res) => {
  const limit = req.query.limit || 0; // get
  const skip = req.query.skip || 0; // get
  console.log(req.body);
  FindAllTableData({
    model: GoodsModel,
    res,
    msg: "查询成功",
    query: {},
    limit,
    skip,
  });
});

module.exports = router;
